import logging
from dataclasses import dataclass

from src.application.category.converters import convert_category_dto_to_entity
from src.application.order.uow import OrderUoW
from src.application.proxy.dto.proxies import ProxiesDTO
from src.application.proxy.interfaces.reader.proxy_reader import GetProxiesFilters
from src.application.server.enums import ServerPrivacy, ServerType
from src.domain.user.value_objects import TelegramUserId, UserId
from src.infrastructure.db.uow import SQLAlchemyUoW

logger = logging.getLogger(__name__)


@dataclass(frozen=True)
class GetAvailableProxies:
    tg_user_id: int
    proxy_type: ServerType | None = None
    proxy_privacy: ServerPrivacy | None = None
    country_id: int | None = None
    provider_id: int | None = None
    category_id: int | None = None
    site_id: int | None = None
    limit: int | None = None


class GetAvailableProxiesHandler:
    """Получаем доступные для аренды прокси"""

    def __init__(
        self,
        *,
        uow: SQLAlchemyUoW,
    ) -> None:
        self._uow = uow

    async def __call__(self, query: GetAvailableProxies) -> ProxiesDTO:
        category = await self._uow.category_reader.get_category_by_id(query.category_id)
        category_entity = convert_category_dto_to_entity(category)
        user = await self._uow.user_repo.acquire_user_by_id(UserId(query.tg_user_id))

        proxies = await self._uow.proxy_reader.get_available_proxies(
            user=user,
            category=category_entity,
            filters=GetProxiesFilters(
                limit=query.limit,
                proxy_type=query.proxy_type,
                proxy_privacy=query.proxy_privacy,
                country_id=query.country_id,
                provider_id=query.provider_id,
                site_id=query.site_id,
                category_id=query.category_id,
            ),
        )

        return ProxiesDTO(proxies=proxies, total=len(proxies), limit=query.limit)
